//
//  ShoppingCarViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/22.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SVProgressHUD
import SwiftyJSON

class ShoppingCarViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,ShoppingTableViewCellDelegate {

    var isCommodityVC = ""
    
    
    var myTableView = UITableView(frame: CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT*0.8-64), style: .Grouped)
    let SHOPPINGCELL = "ShoppingViewCell"
    
    var dataDic = NSDictionary()
    var dataArray = NSMutableArray()
    
    let priceLabel = UILabel()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.automaticallyAdjustsScrollViewInsets = false
        self.creatNavVIew()
        self.view.backgroundColor = UIColor.whiteColor()
        self.navigationController?.navigationBar.barTintColor = UIColor(red: 94/255.0, green: 200/255.0, blue: 252/255.0, alpha: 1)
        self.title = "SHOPPINGCAR"
        
        
        self.getData()
        self.creatTableView()
        self.creatBottomView()
    }
    
    
}

extension ShoppingCarViewController{
    private func getData(){
        var zendID = ""
        if (UserSession.shareInstance.cookie != nil) {
            zendID = UserSession.shareInstance.cookie!
        }
        
        let parma = ["main_page":"shopping_cart","zenid":zendID]
        NetworkTool.shareInstance.request(.GET, urlString: APIBASE, parmas: parma) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                
                
                let dic = result!["data"]as?NSDictionary
                self.dataDic = dic!
                
                let cartArr = dic!["cart"]as?[[String:NSObject]]
                for bigDic in cartArr!{
                    let model = ShoppingCartModel(dictionary: bigDic)
                    self.dataArray.addObject(model)
                }
                self.getTotalPrice()
                self.myTableView.reloadData()
            }else{
                SVProgressHUD.showErrorWithStatus("get cart data error:" + String(error))
                print("get cart data error:" + String(error))
            }
        }
        
        
    
    }
    
    
    func getTotalPrice(){
        priceLabel.text = self.dataDic["total_price"]as?String
    }
}


extension ShoppingCarViewController{
    
    private func creatNavVIew(){
        let leftBtn = UIButton(type: .Custom)
        leftBtn.setImage(UIImage(named: "nav_back"), forState: .Normal)
        leftBtn.frame = CGRectMake(0, 0, 30, 30)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), forControlEvents: .TouchUpInside)
        let item = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = item
    }
    
    func leftBtnClick(){
        if self.isCommodityVC == "yes" {
            self.navigationController?.popViewControllerAnimated(true)
        }else{
            self.dismissViewControllerAnimated(true) {
                
            }
        }
        
    }
}

extension ShoppingCarViewController{
    private func creatTableView(){
        myTableView.delegate = self
        myTableView.dataSource = self
        self.view.addSubview(myTableView)
        
        let nib = UINib(nibName: "ShoppingTableViewCell", bundle: nil)
        
        myTableView.registerNib( nib, forCellReuseIdentifier: SHOPPINGCELL)
        myTableView.separatorStyle = .None
        
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(SHOPPINGCELL, forIndexPath: indexPath)
        cell.selectionStyle = .None
        
        let model = self.dataArray[indexPath.row]as?ShoppingCartModel
        (cell as?ShoppingTableViewCell)?.delegate = self
        (cell as? ShoppingTableViewCell)?.model = model
        
//        let deleteBtn = (cell as? ShoppingTableViewCell)?.viewWithTag(6) as? UIButton
//        deleteBtn?.tag = 100 + indexPath.row
//        
//        let subBtn = (cell as? ShoppingTableViewCell)?.viewWithTag(7) as? UIButton
//        subBtn?.tag = 1000 + indexPath.row
//        
//        let addBtn = (cell as? ShoppingTableViewCell)?.viewWithTag(9) as? UIButton
//        addBtn?.tag = 10000 + indexPath.row
        
        (cell as? ShoppingTableViewCell)?.index = indexPath.row
        
        
        return cell
    }
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return SCREEN_HEIGHT * 0.25
    }
    
    func goToCommodityVC(productID: String, imgStr: String) {
        let commodityVC = CommodityViewController()
        commodityVC.idStr = productID
        commodityVC.productImgView = imgStr
        self.navigationController?.pushViewController(commodityVC, animated: true)
    }
    
    
    func letShoppingVCDeleteTheCell(tag: Int) {
        let index = tag - 100

        let model = self.dataArray[index] as! ShoppingCartModel
        let urlStr = APIBASE + "main_page=cart_actions"
        let parmas = ["act":"remove","basket_id":model.id!,"zenid":UserSession.shareInstance.cookie!]
        NetworkTool.shareInstance.request(.POST, urlString: urlStr, parmas: parmas) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                
                SVProgressHUD.showSuccessWithStatus("Delete the success!")
                
                
                self.dataArray.removeObjectAtIndex(index)
                
                self.myTableView.reloadData()
                self.totalPrice()
                
            }else{
                SVProgressHUD.showErrorWithStatus("delete error:" + String(error))
                print("delete error:" + String(error))
            }
        }
        
        
    }
    
    func letShoppingVCSubTheNumber(tag: Int) {

        let index = tag - 1000

        let model = self.dataArray[index] as! ShoppingCartModel
        let urlStr = APIBASE + "main_page=cart_actions"
        let idStr = "id[\(model.options_id!)]"
        
        var number = Int(model.quantity!)
        if number > 1 {
            number = number! - 1
        }
//        print(String(number!))
        
        let parmas = ["act":"update",idStr:model.options_values_id!,"products_id":model.products_id!,"cart_quantity":String(number!),"zenid":UserSession.shareInstance.cookie!]
        NetworkTool.shareInstance.request(.POST, urlString: urlStr, parmas: parmas) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                self.dataArray.removeAllObjects()
                self.getData()
                self.totalPrice()
                self.myTableView.reloadData()
                
            }else{
                SVProgressHUD.showErrorWithStatus("sub error:" + String(error))
                print("sub error:" + String(error))
            }
        }

        
        
    }
    
    func letShoppingVCAddTheNumber(tag: Int) {

        let index = tag - 10000
        
        let model = self.dataArray[index] as! ShoppingCartModel
        let urlStr = APIBASE + "main_page=cart_actions"
        let idStr = "id[\(model.options_id!)]"
        
        var number = Int(model.quantity!)
        number = number! + 1
        
        let parmas = ["act":"update",idStr:model.options_values_id!,"products_id":model.products_id!,"cart_quantity":String(number!),"zenid":UserSession.shareInstance.cookie!]
        NetworkTool.shareInstance.request(.POST, urlString: urlStr, parmas: parmas) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                self.dataArray.removeAllObjects()
                self.getData()
                self.totalPrice()
                self.myTableView.reloadData()
                
            }else{
                SVProgressHUD.showErrorWithStatus("add error:" + String(error))
                print("add error:" + String(error))
            }
        }
        
    }
    
    
    func totalPrice(){
        
        var price : Float = 0.00
        for model in self.dataArray {
            let shopModel = model as? ShoppingCartModel
            let money = Float((shopModel?.quantity)!)! * self.stringByReplaceWithStr((shopModel?.format_price)!)
            price = price + money
        }
        
        self.priceLabel.text = self.stringWithMoney() + String(format: "%.2f",price)
        
    }
    
    func stringByReplaceWithStr(str:String) -> Float{
        let num = str.stringByReplacingOccurrencesOfString("$", withString: "").stringByReplacingOccurrencesOfString(",", withString: "").stringByReplacingOccurrencesOfString("CAD", withString: "").stringByReplacingOccurrencesOfString("£", withString: "").stringByReplacingOccurrencesOfString("AU", withString: "").stringByReplacingOccurrencesOfString("€", withString: "")
        
        return Float(num)!
    }
    
    func stringWithMoney() -> String{
        var str = ""
        let moneyStr = NSUserDefaults.standardUserDefaults().objectForKey("MONEYINDEX") as? String
        var index = 0
        
        if moneyStr == nil || moneyStr == "" {
            index = 1
        }else{
            index = Int(moneyStr!)!
        }
        
        
        if index == 0 {
            str = "CAD$"
        }else if index == 1{
            str = "$"
        }else if index == 2{
            str = "£"
        }else if index == 3{
            str = "AU$"
        }else{
            str = "€"
        }
        
        return str
    }
}

extension ShoppingCarViewController{
    private func creatBottomView(){
        let bottomView = UIView()
        bottomView.backgroundColor = UIColor.whiteColor()
        bottomView.frame = CGRectMake(0, SCREEN_HEIGHT*0.8, SCREEN_WIDTH, SCREEN_HEIGHT*0.2)
        self.view.addSubview(bottomView)
        
        priceLabel.frame = CGRectMake(SCREEN_WIDTH*0.7, SCREEN_HEIGHT*0.02, SCREEN_WIDTH*0.3, SCREEN_HEIGHT*0.06)
        priceLabel.textAlignment = .Center
        priceLabel.font = UIFont.systemFontOfSize(21)
        bottomView.addSubview(priceLabel)
        
        let processOrderBtn = UIButton(type: .Custom)
        processOrderBtn.frame = CGRectMake(SCREEN_WIDTH*0.05, SCREEN_HEIGHT*0.1, SCREEN_WIDTH*0.9, SCREEN_HEIGHT*0.08)
        processOrderBtn.setTitle("PROCESS ORDER", forState: .Normal)
        processOrderBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        processOrderBtn.backgroundColor = UIColor.blackColor()
        processOrderBtn.addTarget(self, action: #selector(processOrderButtonClick), forControlEvents: .TouchUpInside)
        
        bottomView.addSubview(processOrderBtn)
        
    }
    
//    PROCESSORDER 点击事件
    func processOrderButtonClick(){
        
        if self.dataArray.count == 0 {
            SVProgressHUD.showInfoWithStatus("Shopping cart is empty!")
            return
        }
        
        if UserSession.shareInstance.isLogin == true {
            let processVC = ProcessOrderViewController()
            processVC.dic = self.dataDic
            processVC.allPrice = priceLabel.text
            processVC.cartArray = self.dataArray

            self.navigationController?.pushViewController(processVC, animated: true)
        }else{
            let loginVC = LoginViewController()
            loginVC.dic = self.dataDic
            loginVC.allPrice = priceLabel.text
            loginVC.cartArray = self.dataArray
            loginVC.isShoppingCar = true
            self.navigationController?.pushViewController(loginVC, animated: true)

        }
    }
}












